import re
import os
from itertools import accumulate, tee, islice
import collections

#FIXME unicode

orig = []
ind = 0
result = orig

from collections import deque

class DestructiveIterator:
    def __init__(self, d):
        self.deque = d
    
    def __next__(self):
        if not self.deque:
            raise StopIteration
        return self.deque.popleft()
    
    def __iter__(self):
        return self

'''
def filter(input_iter, output=None):
    pass
'''


def strip_line_numbers(line_iter, **kw):
    for line in line_iter:
        yield re.sub(r'N\d+\s+', '', line)

def joined(lines_iter):
    l = []
    for elt in lines_iter:
        l.append(elt)
        yield elt, os.linesep.join(l)
    
    #one, two = tee(lines_iter)
    #
    #two = accumulate(two, func=lambda *args: os.linesep.join(args))
    #for elt in one:
    #    yield elt, next(two)

class Processor:
    def __init__(self, lines, filters, output=[]):
        self.input = deque(lines)
        self.output = output
        self.filters = [
            f(DestructiveIterator(self.input), output=self.output)
            for f in filters
            ]
    
    def __iter__(self):
        return self
    
    def __next__(self):
        def get_next(filter_):
            try:
                return next(filter_)
            except StopIteration:
                self.filters.pop(
                    self.filters.index(filter_)
                    )
        if not self.filters:
            
            if self.input:
                return self.input.popleft()
            raise StopIteration
        *filters, last = self.filters
        for f in filters:
            to_append = get_next(f)
            self.input.appendleft(to_append)
        to_append = get_next(last)
        self.output.append(to_append)
        return to_append

def start_handler(lines_iter, **kw):
    # yields text
    for line in lines_iter:
        if line == 'START\n':
            break
    for line, text in joined(lines_iter):
        #import ipdb; ipdb.set_trace()
        #if '%' in line:
        if line == '%\n':
            
            yield line
            name = re.findall(r'\'\((O\d+)\)', text)[0]
            yield name
            break
    
    


if __name__ == '__main__':
    with open('O00001.utf8') as f:
        src = deque(f)
        #for out in strip_line_numbers(line_iter):
        #    result.append(out)
    #import ipdb; ipdb.set_trace()
    for step in Processor(src,
                          filters=[strip_line_numbers],
                          output=result):
        pass
    import ipdb; ipdb.set_trace()
    res2 = []
    p = Processor(result,
                  filters=[start_handler],
                  output=res2)
    #try:
        
    for step in p: pass
    #except:
    #    import pdb
    #    pdb.post_mortem()
        #orig = f.read()
    print (res2)
    